//
//  SYDPlaceholderView.m
//  LantaiyuanBus
//
//  Created by lantaiyuan on 16/9/14.
//  Copyright © 2016年 lantaiyuan. All rights reserved.
//

#import "SYDPlaceholderView.h"

@implementation SYDPlaceholderView

-(instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = WHITE_COLOR;
        
        [self setPlaceHolder:@""];
        
        [self setPlaceHolderColor:[UIColor lightGrayColor]];
        //发送通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

-(void)setPlaceHolder:(NSString *)placeHolder{
    
    if (_placeHolder != placeHolder) {
        
        _placeHolder = placeHolder;
        
        [self.placeHolderLbl removeFromSuperview];
        
        self.placeHolderLbl = nil;
        
        [self setNeedsDisplay];
    }
    
}

/**
 *  通知
 */
-(void)textChange:(NSNotification *)notification{
    
    if ([[self placeHolder] length] == 0) {
        return;
    }
    if ([[self text] length] == 0) {
        
        [[self viewWithTag:999] setAlpha:1.0];
        
    }else{
        
        
        [[self viewWithTag:999]setAlpha:0.0];
    }
    
}

- (void)drawRect:(CGRect)rect {
    
    [super drawRect:rect];
    //没有写反馈意见
    if ([[self placeHolder]length] >0) {
        if (_placeHolderLbl == nil) {
            _placeHolderLbl = [[UILabel alloc]initWithFrame:CGRectMake(15, 15, self.bounds.size.width - 16, 0)];
            
            _placeHolderLbl.lineBreakMode = NSLineBreakByWordWrapping;
            
            _placeHolderLbl.numberOfLines = 0;
            _placeHolderLbl.font = self.font;
            _placeHolderLbl.backgroundColor = [UIColor clearColor];
            _placeHolderLbl.textColor = self.placeHolderColor;
            _placeHolderLbl.alpha = 0;
            _placeHolderLbl.tag = 999;
            
            [self addSubview:_placeHolderLbl];
            
        }
        _placeHolderLbl.text = self.placeHolder;
        
        [_placeHolderLbl sizeToFit];
        
        [self sendSubviewToBack:_placeHolderLbl];
    }
    //placeholder存在
    if ([[self text] length] == 0 && [[self placeHolder] length]>0) {
        
        [[self viewWithTag:999] setAlpha:1.0];
    }
}

@end
